Restricting the number of exits from a loop is done in the interests of good structured programming. One break
or goto
statement is acceptable in a loop since this allows, for example, for dual-outcome loops or optimal coding.
Noncompliant code example
With the default threshold of 1:
for (int i = 0; i < 10; i++) {
if (...) {
break; // Compliant
}
else if (...) {
break; // Non-compliant - second jump from loop
}
else {
...
}
}
while (...) {
if (...) {
break; // Compliant
}
if (...) {
break; // Non-compliant - second jump from loop
}
}
Compliant solution
for (int i = 0; i < 10; i++) {
if (...) {
break; // Compliant
}
}
while (...) {
if (...) {
break; // Compliant
}
}